package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.dubbo.api.*;
import com.tanhua.dubbo.pojo.*;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.server.vo.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class IMService {

    @DubboReference(version = "1.0.0")
    private HuanXinApi huanXinApi;

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    @DubboReference(version = "1.0.0")
    private UsersApi usersApi;

    @DubboReference(version = "1.0.0")
    private QuanZiApi quanZiApi;



    @DubboReference(version = "1.0.0")
    private AnnouncementApi announcementApi;

    public UserInfoVo queryUserInfoByUserName(String userName) {
        //根据环信用户名查询用户id
        HuanXinUser huanXinUser = this.huanXinApi.queryHuanXinUserByUserName(userName);

        //根据用户id查询用户信息
        UserInfo userInfo = this.userInfoApi.queryByUserId(huanXinUser.getUserId());

        //封装UserInfoVo
        UserInfoVo userInfoVo = BeanUtil.toBeanIgnoreError(userInfo, UserInfoVo.class);
        userInfoVo.setGender(userInfo.getSex().name().toLowerCase());
        userInfoVo.setMarriage(StrUtil.equals("已婚", userInfo.getMarriage()) ? 1 : 0);
        return userInfoVo;
    }

    /**
     * 添加联系人
     *
     * @param userId
     * @return
     */
    public Object addContacts(Long userId) {
        //注册好友关系到MongoDB
        String result = this.usersApi.saveUsers(UserThreadLocal.get(), userId);
        if (StrUtil.isNotEmpty(result)) {
            //注册好友关系到环信
            Boolean bool = this.huanXinApi.addUserFriend(UserThreadLocal.get(), userId);
            if (bool) {
                return null;
            }
        }
        return ErrorResult.builder().errCode("500").errMessage("添加好友失败！").build();
    }

    /**
     * 查询联系人列表
     *
     * @param page
     * @param pageSize
     * @param keyword  根据关键字搜索
     * @return
     */
    public PageResult queryContactsList(Integer page, Integer pageSize, String keyword) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        Long userId = UserThreadLocal.get();
        List<UserInfo> userInfoList;
        if (StrUtil.isEmpty(keyword)) {
            //按顺序查询，按照添加时间倒序排序
            PageInfo<Users> pageInfo = this.usersApi.queryUsersList(userId, page, pageSize);
            if (CollUtil.isEmpty(pageInfo.getRecords())) {
                return pageResult;
            }
            //获取用户信息列表
            //按照Records列表中的顺序进行输出
            List<Users> records = pageInfo.getRecords();
            userInfoList = this.userInfoApi.queryByUserIdList(CollUtil.getFieldValues(records, "friendId"));
            ArrayList<UserInfo> list = new ArrayList<>();
            for (Users users : records) {
                for (UserInfo userInfo : userInfoList) {
                    if (ObjectUtil.equal(users.getFriendId(),userInfo.getUserId())){
                        list.add(userInfo);
                        break;
                    }
                }
            }
            userInfoList = list;
            //userInfoList = this.userInfoApi.queryByUserIdList(CollUtil.getFieldValues(pageInfo.getRecords(), "friendId"));
        } else {
            // 把所有的联系人查询出来，再进行筛选
            List<Users> usersList = this.usersApi.queryAllUsersList(userId);
            if (CollUtil.isEmpty(usersList)) {
                return pageResult;
            }
            List<Object> friendIdList = CollUtil.getFieldValues(usersList, "friendId");
            userInfoList = this.userInfoApi.queryListLikeNickName(friendIdList, keyword);
        }

        List<UsersVo> result = new ArrayList<>();

        //封装UsersVo
        for (UserInfo userInfo : userInfoList) {
            UsersVo usersVo = BeanUtil.toBeanIgnoreError(userInfo, UsersVo.class);
            usersVo.setUserId("HX_" + userInfo.getUserId());
            usersVo.setGender(userInfo.getSex().name().toLowerCase());
            usersVo.setCity(StrUtil.subBefore(userInfo.getCity(), '-', false));
            result.add(usersVo);
        }

        pageResult.setItems(result);
        return pageResult;
    }

    public Boolean removeUser(Long userId, Long likeUserId) {
        Boolean result = this.usersApi.removeUsers(userId, likeUserId);
        if (result){
            return this.huanXinApi.removeUserFriend(userId, likeUserId);
        }
        return false;
    }


    /**
     * 查询消息点赞列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryLikeCommentList(Integer page, Integer pageSize) {
        Long userId = UserThreadLocal.get();
        PageInfo<Comment> pageInfo = this.quanZiApi.queryLikeCommentListByUser(userId, page, pageSize);
        return this.fillUserCommentList(pageInfo);
    }

    /**
     * 查询消息喜欢列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryLoveCommentList(Integer page, Integer pageSize) {
        Long userId = UserThreadLocal.get();
        PageInfo<Comment> pageInfo = this.quanZiApi.queryLoveCommentListByUser(userId, page, pageSize);
        return this.fillUserCommentList(pageInfo);
    }

    /**
     * 查询消息评论列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryUserCommentList(Integer page, Integer pageSize) {
        Long userId = UserThreadLocal.get();
        PageInfo<Comment> pageInfo = this.quanZiApi.queryCommentListByUser(userId, page, pageSize);
        return this.fillUserCommentList(pageInfo);
    }

    //根据用户id查询用户信息,并填充评论表集合List<Comment>,填充PageResult
    private PageResult fillUserCommentList(PageInfo<Comment> pageInfo){
        PageResult pageResult = new PageResult();
        pageResult.setPage(pageInfo.getPageNum());
        pageResult.setPagesize(pageInfo.getPageSize());

        List<Comment> records = pageInfo.getRecords();
        if(CollUtil.isEmpty(records)){
            //没有查询到数据
            return pageResult;
        }

        List<Object> userIdList = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = this.userInfoApi.queryByUserIdList(userIdList);

        List<MessageCommentVo> messageCommentVoList = new ArrayList<>();
        for (Comment comment : records) {
            for (UserInfo userInfo : userInfoList) {
                if(ObjectUtil.equals(comment.getUserId(), userInfo.getUserId())){
                    MessageCommentVo messageCommentVo = new MessageCommentVo();
                    messageCommentVo.setId(comment.getId().toHexString());
                    messageCommentVo.setAvatar(userInfo.getLogo());
                    messageCommentVo.setNickname(userInfo.getNickName());
                    messageCommentVo.setCreateDate(DateUtil.format(new Date(comment.getCreated()), "yyyy-MM-dd HH:mm"));
                    messageCommentVoList.add(messageCommentVo);
                    break;
                }
            }
        }

        pageResult.setItems(messageCommentVoList);

        return pageResult;
    }


    /**
     * 查询公告列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryMessageAnnouncementList(Integer page, Integer pageSize) {
        IPage<Announcement> announcementPage = this.announcementApi.queryAnnouncementList(page, pageSize);

        List<AnnouncementVo> announcementVoList = new ArrayList<>();

        for (Announcement record : announcementPage.getRecords()) {
            AnnouncementVo announcementVo = new AnnouncementVo();
            announcementVo.setId(record.getId().toString());
            announcementVo.setTitle(record.getTitle());
            announcementVo.setDescription(record.getDescription());
            announcementVo.setCreateDate(DateUtil.format(record.getCreated(), "yyyy-MM-dd HH:mm"));

            announcementVoList.add(announcementVo);
        }

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setItems(announcementVoList);

        return pageResult;
    }
}
